package com.ruoyi.web.handle.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.uuid.UUID;
import com.ruoyi.web.domain.*;
import com.ruoyi.web.domain.vo.AjaxResult;
import com.ruoyi.web.handle.service.GetDataService;
import com.ruoyi.web.mapper.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Service
public class GetDataServiceImpl implements GetDataService {

    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private GuMrGuMapper guMrGuMapper;
    @Autowired
    private GuMrHszgMapper guMrHszgMapper;
    @Autowired
    private GuMrZtgcMapper guMrZtgcMapper;
    @Autowired
    private GuMrDtgcMapper guMrDtgcMapper;
    @Autowired
    private GuErrorLogMapper guErrorLogMapper;
    @Autowired
    private GuMrDapanMapper guMrDapanMapper;
    @Autowired
    private GuMrStockSnapshotMapper guMrStockSnapshotMapper;
    @Autowired
    private GuMrCompanyInfoMapper guMrCompanyInfoMapper;
    @Autowired
    private GuMrTradeDetailMapper guMrTradeDetailMapper;
    @Autowired
    private GuMrMoneyFlowFullMapper guMrMoneyFlowFullMapper;


    @Async
    @Override
    public Boolean getData() {
        RestTemplate restTemplate = new RestTemplate();
        //设置Header
        MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
        headers.add("Content-Type", "application/json;charset=UTF-8");

        //获取每只股票名称及数据
        String url = "http://api.mairuiapi.com/hslt/list/8D57E913-D7A4-4DE8-8E9D-522A095297ED";
        //发起请求,直接返回对象
        Object obj = restTemplate.getForObject(url, Object.class, headers);
        //将object转换为string
        String userListString = JSON.toJSONString(obj);

        //将string封装为对象集合
        List<GuMrGu> guMrGuList = JSONObject.parseArray(userListString,GuMrGu.class);

        if(guMrGuList!=null&&guMrGuList.size()>0){
            guMrGuMapper.truncateTable();
        }
        for (GuMrGu guMrGu : guMrGuList) {
            guMrGu.setId(guMrGu.getDm());
            //根据股票找相关的指数行业
            String code = guMrGu.getDm().replaceAll("[.]|[a-zA-Z]", "");
            String url2 = "http://api.mairuiapi.com/hszg/zg/"+code+"/8D57E913-D7A4-4DE8-8E9D-522A095297ED";
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            logger.info("【获取股票相关行业】---{}",JSON.toJSONString(guMrGu));
            try{
                Object obj2 = restTemplate.getForObject(url2, Object.class, headers);
                //将object转换为string

                String ListString2 = JSON.toJSONString(obj2);

                //将string封装为对象集合
                List<GuMrHszg> guMrHszgsList = JSONObject.parseArray(ListString2,GuMrHszg.class);

                String gn1 = "";
                String gn2 = "";
                for(GuMrHszg guMrHszg : guMrHszgsList){
                    if(gn1.isEmpty()){
                        gn1 = guMrHszg.getCode();
                    } else  {
                        gn1 = gn1+","+guMrHszg.getCode();
                    }
                    if(gn2.isEmpty()){
                        gn2 = guMrHszg.getCode();
                    }else   {
                        gn2 = gn2+","+guMrHszg.getCode();
                    }
                }
                guMrGu.setGn1(gn1);
                guMrGu.setGn2(gn2);
                guMrGu.setCreateTime(DateUtils.getNowDate());
                guMrGuMapper.insertGuMrGu(guMrGu);
            }catch (Exception e){
                logger.error("【获取股票相关行业接口获取出错】---{}",JSON.toJSONString(guMrGu));
                GuErrorLog guErrorLog = new GuErrorLog();
                guErrorLog.setId(UUID.randomUUID().toString().replace("-",""));
                guErrorLog.setCreateTime(DateUtils.getNowDate());
                guErrorLog.setRemark("【获取股票相关行业接口获取出错】---"+JSON.toJSONString(guMrGu));
                guErrorLogMapper.insertGuErrorLog(guErrorLog);
            }

        }
        // 获取所有行业和概念
        String url1 = "http://api.mairuiapi.com/hszg/list/8D57E913-D7A4-4DE8-8E9D-522A095297ED";
        Object obj1 = restTemplate.getForObject(url1, Object.class, headers);
        String ListString3 = JSON.toJSONString(obj1);
        //将string封装为对象集合
        List<GuMrHszg> gumerHszgList = JSONObject.parseArray(ListString3,GuMrHszg.class);
        for( GuMrHszg  guMrHszg : gumerHszgList){
            guMrHszg.setId(guMrHszg.getCode());
            guMrHszgMapper.insertGuMrHszg(guMrHszg);
        }

        //获取涨停，跌停数据
        LocalDate date = LocalDate.now(); // 或者 LocalDate.now()
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String formattedDate = date.format(formatter);
        String url2 ="http://api.mairuiapi.com/hslt/ztgc/"+formattedDate+"/8D57E913-D7A4-4DE8-8E9D-522A095297ED";
        String url3 ="http://api.mairuiapi.com/hslt/dtgc/"+formattedDate+"/8D57E913-D7A4-4DE8-8E9D-522A095297ED";
        Object object3 = restTemplate.getForObject(url2, Object.class, headers);
        Object object4 = restTemplate.getForObject(url3, Object.class, headers);
        String ob3 = JSON.toJSONString(object3);
        String ob4 = JSON.toJSONString(object4);
        List<GuMrZtgc> mrZtgcs = JSONObject.parseArray(ob3,GuMrZtgc.class);
        List<GuMrDtgc>  dtgcs  = JSONObject.parseArray(ob4,GuMrDtgc.class);
        for(GuMrZtgc guMrZtgc : mrZtgcs){
            guMrZtgc.setId(UUID.randomUUID().toString().replace("-",""));
            guMrZtgc.setCreateTime(DateUtils.getNowDate());
            guMrZtgcMapper.insertGuMrZtgc(guMrZtgc);
        }
        for(GuMrDtgc guMrDtgc : dtgcs){
            guMrDtgc.setId(UUID.randomUUID().toString().replace("-",""));
            guMrDtgc.setCreateTime(DateUtils.getNowDate());
            guMrDtgcMapper.insertGuMrDtgc(guMrDtgc);
        }
        return null;
    }

    @Async
    @Override
    public Boolean getZtgc() {
        return null;
    }

    @Async
    @Override
    public Boolean getDtgc() {
       int a = guMrZtgcMapper.selectIsNullBuyData();
       if(a>0){
           return true;
       }
        RestTemplate restTemplate = new RestTemplate();
        MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
        headers.add("Content-Type", "application/json;charset=UTF-8");
        //获取涨停，跌停数据
        LocalDate date = LocalDate.now(); // 或者 LocalDate.now()
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        //String formattedDate = date.format(formatter);
        String formattedDate = "2025-10-24";
        String url2 ="http://api.mairuiapi.com/hslt/ztgc/"+formattedDate+"/8D57E913-D7A4-4DE8-8E9D-522A095297ED";
        String url3 ="http://api.mairuiapi.com/hslt/dtgc/"+formattedDate+"/8D57E913-D7A4-4DE8-8E9D-522A095297ED";
        Object object3 = restTemplate.getForObject(url2, Object.class, headers);
        Object object4 = restTemplate.getForObject(url3, Object.class, headers);
        String ob3 = JSON.toJSONString(object3);
        String ob4 = JSON.toJSONString(object4);
        List<GuMrZtgc> mrZtgcs = JSONObject.parseArray(ob3,GuMrZtgc.class);
        List<GuMrDtgc>  dtgcs  = JSONObject.parseArray(ob4,GuMrDtgc.class);
        for(GuMrZtgc guMrZtgc : mrZtgcs){
            guMrZtgc.setId(UUID.randomUUID().toString().replace("-",""));
            guMrZtgc.setCreateTime(DateUtils.getNowDate());
            guMrZtgcMapper.insertGuMrZtgc(guMrZtgc);
        }
        for(GuMrDtgc guMrDtgc : dtgcs){
            guMrDtgc.setId(UUID.randomUUID().toString().replace("-",""));
            guMrDtgc.setCreateTime(DateUtils.getNowDate());
            guMrDtgcMapper.insertGuMrDtgc(guMrDtgc);
        }
        return true;
    }

    @Async
    @Override
    public Boolean getDapan() {

        int a = guMrDapanMapper.selectIsNullBuyData();
        if(a>0){
            return true;
        }

        RestTemplate restTemplate = new RestTemplate();
        MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
        headers.add("Content-Type", "application/json;charset=UTF-8");
        //获取所有指数
        String url1 ="http://api.mairuiapi.com/hsindex/list/8D57E913-D7A4-4DE8-8E9D-522A095297ED" ;
        Object object = restTemplate.getForObject(url1, Object.class, headers);
        String ob1 = JSON.toJSONString(object);
        List<GuMrGu> guMrGus = JSONObject.parseArray(ob1,GuMrGu.class);
        for(GuMrGu guMrGu : guMrGus){
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }

            try {
                //8D57E913-D7A4-4DE8-8E9D-522A095297ED
                String url2 = "http://api.mairuiapi.com/hsindex/latest/"+guMrGu.getDm()+"/d/8D57E913-D7A4-4DE8-8E9D-522A095297ED" ;
                logger.info("【根据返回的大盘指数轮流获取数据】---{}",JSON.toJSONString(guMrGu));

                Object object2 = restTemplate.getForObject(url2, Object.class, headers);
                String ob2 = JSON.toJSONString(object2);
                List<GuMrDapan> guMrDapans = JSONObject.parseArray(ob2,GuMrDapan.class);
                for(GuMrDapan  guMrDapan : guMrDapans){
                    guMrDapan.setId(UUID.randomUUID().toString().replace("-",""));
                    guMrDapan.setCreateTime(DateUtils.getNowDate());
                    guMrDapan.setZscode(guMrGu.getDm());
                    guMrDapan.setRemark(guMrGu.getMc());
                    guMrDapanMapper.insertGuMrDapan(guMrDapan);
                }
            } catch (Exception e) {
                GuErrorLog guErrorLog = new GuErrorLog();
                guErrorLog.setId(UUID.randomUUID().toString().replace("-",""));
                guErrorLog.setCreateTime(DateUtils.getNowDate());
                guErrorLog.setRemark(e.getMessage()+"=="+guMrGu.getDm());
                guErrorLogMapper.insertGuErrorLog(guErrorLog);

            }

        }
        return null;
    }

    @Override
    public AjaxResult getDzx(String code) throws InterruptedException {
        RestTemplate restTemplate = new RestTemplate();
        MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
        headers.add("Content-Type", "application/json;charset=UTF-8");
        String url = "http://api.mairuiapi.com/hscp/gsjj/"+code+"/8D57E913-D7A4-4DE8-8E9D-522A095297ED";
        GuMrCompanyInfo guMrCompanyInfo = JSONObject.parseObject(url, GuMrCompanyInfo.class);
        guMrCompanyInfo.setCreateTime(DateUtils.getNowDate());
        guMrCompanyInfo.setId(UUID.randomUUID().toString().replace("-",""));
        guMrCompanyInfoMapper.insertGuMrCompanyInfo(guMrCompanyInfo);
        return AjaxResult.success(guMrCompanyInfo);
    }

    /**
     * 当天逐笔交易
     * @param code
     * @return
     * @throws InterruptedException
     */
    @Override
    public Boolean getZbjy(String code) throws InterruptedException {
        RestTemplate restTemplate = new RestTemplate();
        MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
        headers.add("Content-Type", "application/json;charset=UTF-8");
        String url = "http://api.mairuiapi.com/hsrl/zbjy/"+code+"/8D57E913-D7A4-4DE8-8E9D-522A095297ED";
        Object object = restTemplate.getForObject(url, Object.class, headers);
        List<GuMrTradeDetail> guMrTradeDetails = JSONObject.parseArray(JSON.toJSONString(object),GuMrTradeDetail.class);
        for(GuMrTradeDetail guMrTradeDetail : guMrTradeDetails){
            guMrTradeDetail.setCreateTime(DateUtils.getNowDate());
            guMrTradeDetail.setId(UUID.randomUUID().toString().replace("-",""));
            guMrTradeDetail.setCode(code);
            guMrTradeDetailMapper.insertGuMrTradeDetail(guMrTradeDetail);

        }
        return null;
    }

    @Override
    public Boolean getHsstock(String code ,int i ) throws InterruptedException {
        RestTemplate restTemplate = new RestTemplate();
        MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
        headers.add("Content-Type", "application/json;charset=UTF-8");
        String url ="http://api.mairuiapi.com/hsstock/history/transaction/"+code+"/8D57E913-D7A4-4DE8-8E9D-522A095297ED?lt="+i;
        Object object = restTemplate.getForObject(url, Object.class, headers);
        List<GuMrMoneyFlowFull> guMrMoneyFlowFulls = JSONObject.parseArray(JSON.toJSONString(object), GuMrMoneyFlowFull.class);
        for (GuMrMoneyFlowFull guMrMoneyFlowFull : guMrMoneyFlowFulls){
            guMrMoneyFlowFull.setCreateTime(DateUtils.getNowDate());
            guMrMoneyFlowFull.setCode(code);
            guMrMoneyFlowFull.setId(UUID.randomUUID().toString().replace("-",""));
            guMrMoneyFlowFullMapper.insertGuMrMoneyFlowFull(guMrMoneyFlowFull);
        }
        return null;
    }


    @Override
    public Boolean gethsstock() throws InterruptedException {
        return null;
    }

    /**
     * 获取所有日k线
     * @return
     * @throws InterruptedException
     */
    @Override
    public Boolean getssJy() throws InterruptedException {
        RestTemplate restTemplate = new RestTemplate();
        MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
        headers.add("Content-Type", "application/json;charset=UTF-8");
        String url = "http://a.mairuiapi.com/hsrl/ssjy/all/8D57E913-D7A4-4DE8-8E9D-522A095297ED";
        Object object = restTemplate.getForObject(url, Object.class, headers);
        List<GuMrStockSnapshot> guMrStockSnapshotList = JSONObject.parseArray(JSON.toJSONString(object),GuMrStockSnapshot.class);
        for (GuMrStockSnapshot guMrStockSnapshot : guMrStockSnapshotList) {
            guMrStockSnapshot.setId(UUID.randomUUID().toString().replace("-",""));
            guMrStockSnapshot.setCreateTime(DateUtils.getNowDate());
            guMrStockSnapshotMapper.insertGuMrStockSnapshot(guMrStockSnapshot);
        }
        return null;
    }
}
